﻿using System.Collections.Generic;
using Microsoft.SharePoint;

namespace SharePoint.Orm.Metal.Model {
	public class ContentTypeInfo {
		private readonly CodeGeneratorConfiguration _config;
		private readonly SPContentType _contentType;
		private readonly List<ContentTypeFieldInfo> _fields = new List<ContentTypeFieldInfo>();
		private readonly List<ContentTypeLookupFieldInfo> _lookupFields = new List<ContentTypeLookupFieldInfo>();

		public ContentTypeInfo(CodeGeneratorConfiguration config, SiteInfo siteInfo, SPContentType contentType) {
			_config = config;
			_contentType = contentType;
			ClassName = config.NameRewriter.ToContentTypeName(_contentType, null);
			foreach (SPField field in _contentType.Fields) {
				if (field.Id == SPBuiltInFieldId.ContentType
					|| field.Id == SPBuiltInFieldId.LinkTitle
					|| field.Id == SPBuiltInFieldId.LinkTitleNoMenu) {
					continue;
				}
				if (field.Type == SPFieldType.Lookup) {
					LookupFields.Add(new ContentTypeLookupFieldInfo(config, siteInfo, field));
				} else {
					_fields.Add(new ContentTypeFieldInfo(config, siteInfo, field));
				}
			}
		}

		public string ClassName { get; set; }

		public string FileName {
			get { return ClassName + _config.ContentTypeFileNameSuffix + ".cs"; }
		}

		public string NamespaceName {
			get { return _config.ContentTypeNamespaceName; }
		}

		public string ContentTypeId {
			get { return _contentType.Id.ToString(); }
		}

		public string ContentTypeName {
			get { return _contentType.Name; }
		}

		public IEnumerable<ContentTypeFieldInfo> Fields {
			get { return _fields; }
		}

		public SPContentType ContentType {
			get {
				return _contentType;
			}
		}

		public List<ContentTypeLookupFieldInfo> LookupFields {
			get { return _lookupFields; }
		}

		public override bool Equals(object obj) {
			if (obj is ContentTypeInfo) {
				ContentTypeInfo c = (ContentTypeInfo)obj;
				return _contentType.Id.Equals(c._contentType.Id);
			}
			return base.Equals(obj);
		}

		public override int GetHashCode() {
			return _contentType.Id.GetHashCode();
		}
	}
}
